<template>
  <div class="main-materialQuery">
    <div class="layui-tab layui-tab-brief" lay-filter="test-handle">
      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="search">查询</li>
        <li lay-id="result">显示结果</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">

          <div style="display:flex; padding: 15px 0; border-bottom: 1px solid #fff;">
            <div class="layui-form-item" style="margin-bottom: 0;">
              <label class="layui-form-label">类型:</label>
              <div class="layui-input-block">
                <select id="caizhiSearch_layerSelect" style="width:150px; height:30px; color:black;"
                        @change="handleSelectChange">
                  <option style="color:#000" value="">请选择</option>
                </select>
              </div>
            </div>
            <div style="width:33%; text-align: center; " id="caizhiType">
            </div>
            <div style="width:33%; text-align: center; ">
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(1)">全选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(-1)">全不选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(0)">反选
              </button>
            </div>

          </div>
          <div class="layui-row" style="padding: 15px 0; border-bottom: 1px solid #fff;">
            <div class="layui-col-md6 layui-col-md-offset1">
              <input type="button" class="btn btn-primary" value="矩形" @click="drawRectangle"/>
              <input type="button" class="btn btn-primary" value="面" @click="drawPolygon"/>
              <input type="button" class="btn btn-primary" value="圆" @click="drawCircle"/>
              <input type="button" class="btn btn-primary" value="清除" @click="clearDraw"/>
            </div>
          </div>
        </div>
        <div class="layui-tab-item">
          <table
              id="table"
              data-toggle="table"
              data-height="550"
              data-width="430"
              data-search="true"
              data-pagination="true"
              style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
          >
            <thead id="thead" style="color:#fff;">

            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import clearWindow from "@/components/js/clearWindow";
import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";
import {highLightForMaterialQuery} from "@/components/js/highLight";
// eslint-disable-next-line no-unused-vars
let from = null
let $table = null
// eslint-disable-next-line no-unused-vars
let openLayer_caizhiSearch = null
// eslint-disable-next-line no-unused-vars
let openlayerTable = null
export default {
  name: "materialQuery",
  components: {},
  data() {
    return {};
  },
  mounted() {
    openLayer_caizhiSearch = null;
    $table && $table.bootstrapTable('destroy')
    $table = null;
    clearWindow()
    // 初始化面板
    let html = layersMap.filter(l => l.type.indexOf('线') > -1).map(layer => {
      return ` <option style="color:#000" value="${layer.pipelineType}">${layer.type}</option>`
    }).join('')
    $('#caizhiSearch_layerSelect').html(html)
  },
  methods: {
    clearDraw() {
      window.viewer.dadi.draw.clearDraw();
      from = null;
    },
    hideLayerContent() {
      this.$emit('hidden')
    },
    showLayerContent() {
      this.$emit('show')
    },
    handleSelectChange(e) {
      let url = layersMap.find(l => l.pipelineType === e.target.value).url
      fetchData(url).then(r => {
        let options = [...new Set(r.features.map(f => {
          return f['properties']['材质']
        }))]
        let html = options.map(o => {
          return `<label class="btn btn-primary" style="margin: 3px 0; ">
                                    <input class="caizhi-search-type" type="checkbox" value="${o}" > ${o}
                                </label>
                                 `
        }).join('')
        $('#caizhiType').html(html)
      })
    },
    allSelect(flag) {
      let els = $('.caizhi-search-type')
      if (flag == 1) {
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = true
        }
      } else if (flag == -1) {
        $('.caizhi-search-type').attr('checked', false)
      } else { // 反选
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = !element.checked
        }
      }
    },
    allowSearch() {
      let els = $('.caizhi-search-type')
      let caizhiTypes = []
      for (let index = 0; index < els.length; index++) {
        const element = els[index];
        if (element.checked) {
          caizhiTypes.push(element.value)
        }
      }

      if (caizhiTypes.length == 0) {
        layui.layer.alert('至少勾选一类材质进行查询！')
        return false;
      }
      return true;
    },
    drawRectangle() {
      if (this.allowSearch()) {
        this.clearDraw();
        this.hideLayerContent()
        window.viewer.dadi.draw.startDraw({
          type: "rectangle",
          style: {
            color: "#ffff00",
            opacity: 0.2,
            clampToGround: true,
          },
          success: () => {
            this.handleSearch()
            this.showLayerContent()
          }
        });
      }
    },
    async handleSearch() {
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()
      let els = $('.caizhi-search-type')
      let caizhiTypes = []
      for (let index = 0; index < els.length; index++) {
        const element = els[index];
        if (element.checked) {
          caizhiTypes.push(element.value)
        }
      }

      if (caizhiTypes.length == 0) {
        layui.layer.alert('至少勾选一类材质进行查询！')
        return;
      }
      // 求from
      if (drawGeojson.features[0].properties.type === 'circle') {
        from = turf.buffer(turf.feature(drawGeojson.features[0].geometry), Number(drawGeojson.features[0].properties.style.radius) / 1000, {units: 'kilometers'})
      } else if (drawGeojson.features[0].properties.type === 'polygon') {
        from = turf.feature(drawGeojson.features[0].geometry)
      } else if (drawGeojson.features[0].properties.type === 'rectangle') {
        let geo = drawGeojson.features[0].geometry.coordinates.reduce(function (a, b) {
          a.splice(-1)
          b.splice(-1)
          return a.concat(b)
        })
        from = turf.bboxPolygon(geo)
      }

      let properties = [];

      let mylayer = layersMap.find(l => l.pipelineType === $('#caizhiSearch_layerSelect').val())
      if (mylayer) {
        const r = await fetchData(mylayer.url)
        r.features.forEach(fea => {
          // 空间筛选
          let to = turf.feature(fea.geometry)
          let withIntersect = turf.booleanIntersects(to, from);
          if (withIntersect) {
            let caizhi = fea.properties['材质']
            if (caizhiTypes.includes(caizhi)) {
              properties.push({...fea.properties,})
            }
          }
        })

        if (properties.length === 0) {
          layui.layer.msg('没有查询到符合条件的管径！')
          return;
        }

        refreshTable(properties)
        layui.element.tabChange('test-handle', 'result'); // 切换到：标签3
      }

      function refreshTable(tableArr) {
        $table = $('#table');
        let thead = `<tr>`
        Object.keys(tableArr[0]).forEach(key => {
          thead += `<th data-field="${key}">${key}</th>`
        })
        thead += `</tr>`
        $table.bootstrapTable('destroy')
        $('#thead').html(thead)
        $table.bootstrapTable({
          data: tableArr,
          // eslint-disable-next-line no-unused-vars
          onClickRow: (row, $element) => {
            highLightForMaterialQuery(row)
          }
        })
        $table.bootstrapTable('refresh')
      }

    },
    drawCircle() {
      if (this.allowSearch()) {
        this.clearDraw();
        this.hideLayerContent()
        window.viewer.dadi.draw.startDraw({
          type: "circle",
          style: {
            color: "#ffff00",
            opacity: 0.2,
            clampToGround: true,
          },
          success: () => {
            this.handleSearch()
            this.showLayerContent()
          }
        });
      }
    },
    drawPolygon() {
      if (this.allowSearch()) {
        this.clearDraw();
        this.hideLayerContent()
        window.viewer.dadi.draw.startDraw({
          type: "polygon",
          style: {
            color: "#ffff00",
            opacity: 0.2,
            clampToGround: true,
          },
          success: () => {
            this.handleSearch()
            this.showLayerContent()
          }
        });
      }
    }
  },
  watch: {},
  computed: {},
  beforeDestroy() {
    this.clearDraw()
    clearWindow()
  },
}
</script>

<style scoped>
.main-materialQuery {
  position: relative;
  height: 100%;
  width: 100%;
}
</style>
